﻿/// <summary>
/// https://leetcode-cn.com/problems/zigzag-conversion/
/// </summary>
public class Solution
{
    private class Table
    {
        private class Line
        {
            private readonly Dictionary<int, char> dic = new Dictionary<int, char>();
            public void Put(int position, char str)
            {
                if (!this.dic.TryAdd(position, str))
                    this.dic[position] = str;
            }
            public override string ToString()
            {
                System.Text.StringBuilder stringBuilder = new();
                foreach (var item in this.dic.OrderBy((item) => item.Key))
                    _ = stringBuilder.Append(item.Value);
                return stringBuilder.ToString();
            }
        }

        private readonly Line[] lines;
        public Table(int rowCount)
        {
            this.lines = new Line[rowCount];
            for (int i = 0; i < rowCount; i++)
                this.lines[i] = new Line();
        }
        public void Put(int row, int col, char str)
        {
            this.lines[row].Put(col, str);
        }
        public override string ToString()
        {
            System.Text.StringBuilder stringBuilder = new();
            foreach (var line in this.lines)
                _ = stringBuilder.Append(line.ToString());
            return stringBuilder.ToString();
        }
    }

    public string Convert(string s, int numRows)
    {
        if (numRows == 1)
            return s;

        var table = new Table(numRows);

        int i = 0;
        int col = 0;
        int row = 0;
        for (; i < s.Length;)
        {
            for (; row < numRows && i < s.Length; row++)
            {
                table.Put(row, col, s[i++]);
            }

            row -= 2;
            for (; row >= 0 && i < s.Length; row--)
            {
                col++;
                table.Put(row, col, s[i++]);
            }

            row += 2;
        }
        return table.ToString();
    }
}